package com.university.report.user.filter;

import com.university.report.common.utils.JwtUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName health_report
 * @Author Jinondo
 * @Date 2021/6/16 18:23
 */
public class JWTValidationFilter extends BasicAuthenticationFilter {


    /**
     * 获取redisTemplate
     */
    RedisTemplate redisTemplate2;


    public JWTValidationFilter(AuthenticationManager authenticationManager,RedisTemplate redisTemplate2) {
        super(authenticationManager);
        this.redisTemplate2 = redisTemplate2;
    }
    /**
     * 过滤请求验证
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        SecurityContextHolder.getContext().setAuthentication(setAuthentication(token));
        super.doFilterInternal(request, response, chain);
    }

    /**
     * 验证token 并且验证权限
     * @param token
     * @return
     */
    private UsernamePasswordAuthenticationToken setAuthentication(String token) {


        String username = JwtUtil.getUsername(token);
        if (username == null) {
            return null;
        }

        //拼接存到redis中的Key中
        String accessKey=JwtUtil.ACCESS_TOKEN+":"+token;
        //验证redis中的token得值是否存在
        if(!redisTemplate2.hasKey(accessKey)){
            //登录失败
            System.out.println("不会是这里的吧？");
            return null;
        }
        String currentTime = String.valueOf(System.currentTimeMillis());
        //往拼接存到redis中的Key存value值
        redisTemplate2.opsForValue().set(accessKey,currentTime);
        //设置redis key的过期时间 2 天
        redisTemplate2.expire(accessKey,2, TimeUnit.DAYS);

        List<SimpleGrantedAuthority> userRoleList = JwtUtil.getUserAuthorities(token);
        System.out.println(userRoleList);
        return new UsernamePasswordAuthenticationToken(username, null, userRoleList);
    }
}
